const Topic = require('../models/topics');
const User = require('../models/users');
const Question = require('../models/questionSchema');

class TopicsCtl{
    //话题查询
    async find(ctx){
        //limit 第几个开始  skip跳过多少个取多少个  Math.max选最大的一项 RegExp正则匹配
        const { per_page = 10 } = ctx.query;
        const page = Math.max(ctx.query.page * 1,1)-1;
        const perPage = Math.max(per_page * 1,1);
        ctx.body = await Topic.find({name: new RegExp(ctx.query.q)}).limit(perPage).skip(page * perPage);
    }
    //查询某个话题可存在
    async checkTopicExist(ctx, next){
        const topic = await Topic.findById(ctx.params.id);
        if(!topic){ ctx.throw(404,'话题不存在')}
        await next();
    }
    //查询某个话题
    async findById(ctx){
        const { fields = '' } = ctx.query;
        const seletFields = fields.split(';').filter(f => f).map(f => '+' + f).join("");
        const topic = await Topic.findById(ctx.params.id).select(seletFields);
        ctx.body = topic;
    }
    //创建话题
    async create(ctx){
        ctx.verifyParams({
            name: { type: 'string', required: true },
            avatar_url: { type: 'string', required: false},
            introduction: { type: 'string', required: false},
        })
        const topic = await new Topic(ctx.request.body).save();
        ctx.body = topic;
    }
    //修改话题
    async update(ctx){
        ctx.verifyParams({
            name: { type: 'string', required: false },
            avatar_url: { type: 'string', required: false},
            introduction: { type: 'string', required: false},
        })
        const topic = await Topic.findByIdAndUpdate(ctx.params.id, ctx.request.body);
        //这个topic是更新前的信息 要跟新后的信息需要自己去撸 这里不重要
        ctx.body = topic;
    }

    //获取话题的粉丝
    async listTopicFollower(ctx){
        const user = await User.find({ followingTopics: ctx.params.id });//获取特定ID所有的用户
        ctx.body = user;
    }

    //列出问题列表
    async listQuestions(ctx){
        const questions = await Question.find({topics:ctx.params.id})
        ctx.body = questions;
    }
}

module.exports=new TopicsCtl();